//
//  HMStatuPictureView.swift
//  WymanWeibo
//
//  Created by wyman on 16/4/14.
//  Copyright © 2016年 wyman. All rights reserved.
//

import UIKit

private let HMStatusPictureViewCellMarin: CGFloat = 4

private let HMStatusPictureViewMaxColumn = 3

private let HMStatusPictureViewItemWH = (UIScreen.mainScreen()).bounds.width - 2*HMStatusCellMargin - (CGFloat(HMStatusPictureViewMaxColumn)-1)*HMStatusPictureViewCellMarin / CGFloat(HMStatusPictureViewMaxColumn)


class HMStatuPictureView: UICollectionView {

    var pictureURLs: [NSURL]? {
        didSet{
    
        let size = calcViewSize()
            
        self.snp_updateConstraints { (make) in
            make.size.equalTo(size)
            }
        HMPrint("配图大小:\(size)")
        }
    }
  
    //计算配图的宽高
    private func calcViewSize() -> CGSize{
    
        layout.itemSize = CGSize(width: HMStatusPictureViewItemWH, height: HMStatusPictureViewItemWH)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        
        //判断图片的数量
        let count = pictureURLs?.count ?? 0
        
        if count == 0 {
            HMPrint("没有图片")
            return CGSizeZero
    
        }
        
        if count == 1 {
            let size = CGSize(width: 180, height: 90)
            layout.itemSize = size
            return size
        }
        
        layout.minimumInteritemSpacing = HMStatusPictureViewCellMarin
        layout.minimumLineSpacing = HMStatusPictureViewCellMarin
        
        var colum = HMStatusPictureViewMaxColumn
        
        if count == 2 || count == 4 {
            colum = 2
        }
    
        let row = (count + colum - 1)/colum
        
        let width = CGFloat(colum)*HMStatusPictureViewItemWH + (CGFloat(colum)-1) * HMStatusPictureViewCellMarin
        
        let height = CGFloat(row) * HMStatusPictureViewItemWH + (CGFloat(row) - 1) * HMStatusPictureViewCellMarin
        return CGSize(width: width, height: height)
        
    }
    
    
    
    //设置一个flowlayout
    private var layout = UICollectionViewFlowLayout()
    
    init(){
    super.init(frame: CGRectZero, collectionViewLayout: layout)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
